package hse.jack.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.FieldsDocumentPart;
import org.apache.poi.hwpf.usermodel.Field;
import org.apache.poi.hwpf.usermodel.Fields;
import org.apache.poi.hwpf.usermodel.Range;

/**
 * <b>操作word document工具类</b>
 * 
 * @author jack
 * @date 2013年1月31日16:25:19
 * @version 1.0 http://www.laokboke.net/2011/10/29/java-poi-word/
 */
public class WrodDocumentUtil {

	public static void writeWordDocument(String path,
			HttpServletResponse response) {
		InputStream is = null;
		ServletOutputStream servletOS=null;
		String fileDir = null;
		try {
			is = new FileInputStream(new File(path));
			HWPFDocument hdt = new HWPFDocument(is);
			Fields fields = hdt.getFields();
			Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN)
					.iterator();
			while (it.hasNext()) {
				System.out.println(it.next().getType());
			}
			// 替换读取到的word模板内容的指定字段
			Range range = hdt.getRange();
			Map<String, String> map = new HashMap<String, String>();
			map.put("title", "老k博客");
			map.put("blog_name", "老k博客");
			map.put("domain_name", "laokboke.net");
			map.put("description", "是一个专注于wordpress、java、gis、建站、网站推广、seo的IT博客。");
			for (Map.Entry<String, String> entry : map.entrySet()) {
				range.replaceText(entry.getKey(), entry.getValue());
			}

			// 输出word内容文件流，提供下载
			response.reset();
			response.setContentType("application/x-msdownload");
			response.addHeader("Content-Disposition",
					"attachment; filename=\"laokboke.doc\"");
			ByteArrayOutputStream ostream = new ByteArrayOutputStream();
			servletOS = response.getOutputStream();
			hdt.write(ostream);
			servletOS.write(ostream.toByteArray());
			servletOS.flush();
			servletOS.close();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}
}
